<template>
  <dialog-editor ref="dialog" :width="99" :top='top' :col-flag-func="true" close-on-press-escape	></dialog-editor>
</template>

<script>
import DialogEditor from '@/components/DialogEditor'
import dialogMixins from '@/utils/commonDialogMixins'
import {btnBlur} from '@/utils'
import {mRequest, mRequestPromise} from '@/utils/request'
import moment from 'moment';
import {join} from 'ramda'

export default {
  mixins: [dialogMixins],
  components: {DialogEditor},

  data() {
    return {
      deepCategoryMap: {},
      relateDeepCategoryMap: {},
      productInfoMap: {},
      purchaseTypeMap: {
        0: '通货',
        1: '现模',
        2: '开模'
      },
      orderDetailStatusMap: {
        "-1":'缺货（待采购)',
         0:'待配货',
        15:'采购中',
        20:'未出货',
        50:'部分发货',
        55:'已全出货',
        66:'已签收',
        90:'客户退货',
        99:'客户取消'
      },
      top: '3vh',
      dataFormConfig: {
        id: {
          hidden: true
        },
        contractTime: {
          label: '合同日期',
          type: 'date',
          changedCallback: this.contractTimeChangedHandler
        },
        clientId: {
          label: '客户',
          list: [],
          type: 'list',
          placeholder: '请选择客户',
          isNeedAdd: true,
          addNewItemFunc: this.addNewClientInfo
        },
        clientContractNo: {
          label: '客户合同编号'
        },
        contractNo: {
          hidden: true,
          label: '合同编号',
          disabled: true
        },
        deliveryTime: {
          label: '交付日期',
          type: 'date'
        },
        taxInclusive: {
          label: '含税价',
          type: 'radio',
          radioBorder: false,
          radioList: [
            {label: 0, text: '不含税'},
            {label: 1, text: '含税'}
          ],
          default: 0
        },
        transportWay: {
          label: '运输方式',
          type: 'radio',
          radioBorder: false,
          radioList: [
            {label: 0, text: '供方承担(含运费)'},
            {label: 1, text: '需方自提（不含运费）'}
          ],
          default: 0
        },
        currencyType:{
          label: '结算货币',
          type: 'radio',
          showInMultiMode: true,
          radioList: [
            {label: 0, text: '人民币（CNY）'},
            {label: 1, text: '美元（USD）'},
          ],
          default: 0
        },
        totalAmount: {
          label: '合同总价',
          max: 10000000,
          type: 'number',
          disabled: true
        },

        contractStatus: {
          label: '合同状态',
          type: 'radio',
          radioBorder: false,
          radioList: [
            {label: 0, text: '草稿'},
            {label: 1, text: '客户已确认'},
            {label: 4, text: '已收订金'},
            {label: 88, text: '已收尾款'},
            {label: 99, text: '客户取消'}
          ],
          default: 1
        },

     /*   orderStatus: {
          label: '订单状态',
          type: 'radio',
          radioBorder: false,
          radioList: [
            {text: '待采购', label: -1},
            {text: '待配货', label: 0},
            {text: '采购中', label: 15},
            {text: '未出货', label: 20},
            {text: '部分发货',label: 50,},
            {text: '已全出货',label: 55 },
            {text: '已签收', label: 66},
            {text: '客户退货', label: 90},
            {text: '客户取消', label: 99}
          ],
          default: -1
        },*/
        remark: {
          label: '备注',
          placeholder: '请输入备注'
        },
        boxPackText: {
          label: '箱唛描述',
          placeholder: '请输入箱唛'
        },
        // checkProductId:{
        //   label: '查询产品编号',
        //   list: [],
        //   type: 'list',
        //   placeholder: '查询产品编号',
        //   isNeedLook: true,
        //   lookItemInfoFunc: this.lookProductInfo,
        // },
        clientContractFilePath: {
          label: '客户合同文件',
          type: 'uploadImage',
          imageType: 'uploadProductImage'
        },
        // sampleImage: {
        //   label: '样品图片',
        //   type: 'uploadScreenshot',
        //   imageType: 'uploadProductImage'
        // },
        tableListData: {
          type: 'table',
          data: [],
          column: {
            productNo:{
              label: '商品编号',
            },
            unitPrice: {
              label: '单价',
            },
            orderProductNumber: {
              label: '订单数量（只）',
            },
            totalPrice:{
              label: '总价',
            },
            statusStr:{
              label: '状态',
            },
            // productBatchNoQueueId:{
            //   label: '批号',
            // },
            purchaseTypeStr:{
              label: '订单模式',
            },
            modelAmount:{
              label: '开模费用',
            },
            proofingAmount:{
              label: '开模费用',
            },
            groupType:{
              label: '配件组合',
            },
            productWeight: {
              label: '克重',
              width: 120
            },
            deepCategory:{
              label: '光瓶深加工工艺',
            },
       /*     bottleOutDiameter: {
              label: '瓶口外径',
              width: 120
            },*/
            remark: {
              label: '备注'
            }
          },
          operate: {
            addOneLine: {
              label: '新增订单产品',
              icon: 'el-icon-edit',
              type: 'primary',
              clickHandler: this.addNewProductInfo
            },
            deleteOneLine: {
              label: '删除选中的订单',
              icon: 'el-icon-delete',
              type: 'danger',
              clickHandler: this.deleteProductInfo
            },
            editOneLine: {
              label: '修改选中的订单',
              icon: 'el-icon-edit-outline',
              type: 'success',
              clickHandler: this.editProductInfo
            },
            copyOneLine: {
              label: '复制选中的订单',
              icon: 'el-icon-edit-outline',
              type: 'warning',
              clickHandler: this.copyProductInfo
            }
          }
        }
      }
    }
  },
  methods: {
    async contractTimeChangedHandler(date) {
      const res = await mRequestPromise('contractApi/contractNoGetByContractTime', {contractTime: date})
      const contractNo = this.R.path(['data', 'contractNo'], res)

      if (!contractNo) {
        return
      }
    //  const deliveryTime = moment(date).add(45, 'days').format('YYYY-MM-DD');

      this.dataForm.contractNo = contractNo
   //   this.dataForm.deliveryTime = deliveryTime
    },
    editProductInfo(selection, evt) {
      const tmpItem = this.R.head(selection)

      if (this.R.isNil(tmpItem)) {
        return
      }
      const tmpItemIndex = this.dataForm.tableListData.indexOf(tmpItem)

      if (tmpItemIndex === -1) {
        return
      }
      const cb = (newValue) => {
        const tmpValue = this.productOrderHandler(newValue)

        this.dataForm.tableListData.splice(tmpItemIndex, 1, tmpValue)
        this.contractTotalPriceSet()
      }
      this.$parent.openOrderDialog(tmpItem, cb)
      btnBlur(evt)
    },
    copyProductInfo(selection, evt) {
      const tmpItem = this.R.head(selection)
      if (this.R.isNil(tmpItem)) {
        return
      }
      const tmpItemIndex = this.dataForm.tableListData.indexOf(tmpItem)

      if (tmpItemIndex === -1) {
        return
      }
      const cb = (newValue) => {
        const tmpValue = this.productOrderHandler(newValue)

        this.dataForm.tableListData.push(tmpValue)
        this.contractTotalPriceSet()
      }
      this.$parent.openOrderDialog(tmpItem, cb)
      btnBlur(evt)
    },

    productOrderHandler(newValue) {
      newValue.deepCategory = ''
      if (newValue.deepStatus != 0) {
        let deepCategoryList = this.R.propOr([], 'deepCategoryList', newValue)
        newValue.deepCategory = deepCategoryList.map(item => {
          let deepCategoryIdList = this.R.prop('deepCategoryIdList', item)
          let deepCategoryNameList=  deepCategoryIdList.map(deepCategoryId => {
            return this.deepCategoryMap[deepCategoryId] ? this.deepCategoryMap[deepCategoryId] : ''
          }).join(',')
          let customerRequire = this.R.propOr('', 'customerRequire', item)
          let purchaseNumber = this.R.prop('purchaseNumber', item)
          return deepCategoryNameList + '-' + customerRequire + '-' + purchaseNumber + '只'
        }).join('; ')

        deepCategoryList = []
      }
      newValue.groupType = ''
      if (newValue.relateDeepStatus != 0) {
        let relateDeepCategoryList = this.R.propOr([], 'relateDeepCategoryList', newValue)
        console.log("relateDeepCategoryList   "+JSON.stringify(relateDeepCategoryList))

        if (relateDeepCategoryList.length > 0) {
          newValue.groupType = relateDeepCategoryList.map(item => {

            let customerRequire = this.R.prop('customerRequire', item)
            let productId = this.R.prop('productId', item)

            let relateDeepCategoryId = this.R.prop('relateDeepCategoryId', item)
            let purchaseNumber = this.R.prop('purchaseNumber', item)
            if (productId) {
              let productNo = this.productInfoMap[productId]
              if (relateDeepCategoryId) {
                if (customerRequire) {
                  return productNo + '-' + this.relateDeepCategoryMap[relateDeepCategoryId] + '-' + customerRequire + '-' + purchaseNumber + '只'

                }else {
                  return productNo + '-' +this.relateDeepCategoryMap[relateDeepCategoryId]+ '-' + purchaseNumber + '只'
                }

              }else {
                if (customerRequire) {
                  return productNo + '-' + customerRequire+ '-' + purchaseNumber + '只'

                }else {
                  return productNo+ '-' + purchaseNumber + '只'
                }

              }

            }else {
              this.$message.error('检测到 该订单的产品编号为空，请重新选择')
              if (relateDeepCategoryId) {
                if (customerRequire) {
                  return this.relateDeepCategoryMap[relateDeepCategoryId]+'-'+ customerRequire+ '-' + purchaseNumber + '只 产品编号为空'
                }else {
                  return   purchaseNumber + '只 产品编号为空'
                }
              }else {
                if (customerRequire) {
                  return  customerRequire + purchaseNumber + '只 产品编号为空'
                }
              }

            }
          }).join('; ')
        }
        relateDeepCategoryList = []
      }

      newValue.unitPrice = parseFloat(Number(newValue.unitPrice).toFixed(3))
      newValue.totalPrice = (newValue.unitPrice * newValue.orderProductNumber + newValue.modelAmount + newValue.proofingAmount).toFixed(3)

      newValue.productNo = this.productInfoMap[newValue.productId]
      if (this.R.isNil(newValue.productNo)) {
        mRequest("productApi/productInfoInfo", {id: newValue.productId}, (res) => {
          const productInfo= this.R.pathOr([], ['data', 'productInfo'], res)
          if (productInfo) {
            newValue.productNo = productInfo.productNo
            this.productInfoMap[newValue.productId] = newValue.productNo
          }
        })
      }
      if (window.R.isEmpty(newValue.capSuitInfoList)) {
        newValue.capSuitInfoList = null
      }
      if (window.R.isEmpty(newValue.bottleSuitInfoList)) {
        newValue.bottleSuitInfoList = null
      }
      if (newValue.status == -1) {
        newValue.statusStr='待采购'
      }else {
        newValue.statusStr = this.orderDetailStatusMap[newValue.status]
      }
      newValue.purchaseTypeStr= this.purchaseTypeMap[newValue.needPurchaseType]

      return newValue
    },
    deleteProductInfo(selection, evt) {
      const selectionIndex = selection.map(item => this.dataForm.tableListData.indexOf(item)).sort((a, b) => {
        return a - b;
      })

      for (let i = selectionIndex.length - 1; i >= 0; i--) {
        this.dataForm.tableListData.splice(selectionIndex[i], 1)
      }
      this.contractTotalPriceSet()
      btnBlur(evt)
    },
    addNewProductInfo(_, evt) {
      const cb = (newValue) => {
        const tmpValue = this.productOrderHandler(newValue)
        this.dataForm.tableListData.push(tmpValue)

        if (tmpValue.relateDeepStatus !=0) {
          console.log(JSON.stringify(tmpValue.relateDeepCategoryList))
        }


        this.contractTotalPriceSet()
      }
      this.$parent.openOrderDialog({'clientId':this.dataForm.clientId}, cb)
      btnBlur(evt)
    },
    contractTotalPriceSet() {
      const orderPriceList = this.dataForm.tableListData.map(window.R.propOr(0, 'totalPrice'))
      const orderProductNumberList = this.dataForm.tableListData.map(window.R.propOr(0, 'orderProductNumber'))

      this.dataForm.totalAmount = window.R.reduce(window.R.add, 0, orderPriceList)
      this.dataForm.realSaleNumber = window.R.reduce(window.R.add, 0, orderProductNumberList)
    },
    addNewClientInfo() {
      const cb = (newValue) => {
        this.initClientInfoList()
        this.dataForm.clientId = newValue.id
      }
      this.$parent.openClientInfoDialog(cb)
    },
    deepCategoryMapInit() {
      mRequest('deepApi/deepCategoryList', {}, (res) => {
        const tmpList = this.R.pathOr([], ['data', 'list'], res)

        tmpList.forEach(item => {
          const {id, name} = item

          this.deepCategoryMap[id] = name
        })
      })
    },
    relateDeepCategoryMapInit() {
      mRequest('relateApi/getRelateDeepCategoryList', {}, (res) => {
        const tmpList = this.R.pathOr([], ['data', 'list'], res)

        tmpList.forEach(item => {
          const {id, name} = item

          this.relateDeepCategoryMap[id] = name
        })
      })
    },
    productInfoMapInit() {
      mRequest('productApi/getProductInfoList', {}, (res) => {
        const productInfoList = this.R.pathOr([], ['data', 'list'], res)
        //   this.dataFormConfig['checkProductId'].list = productInfoList
        productInfoList.forEach(item => {
          const {id, name} = item
          this.productInfoMap[id] = name
        })
      })
      mRequest('orderApi/getTradeOrderStatusList', {}, (res) => {
        const orderDetailStatusList = this.R.pathOr([], ['data', 'list'], res)
        //   this.dataFormConfig['checkProductId'].list = productInfoList
        orderDetailStatusList.forEach(item => {
          const {id, name} = item
          this.orderDetailStatusMap[id] = name
        })

      })
    },
    // lookProductInfo(item) {
    //   const cb = (newValue) => {
    //     this.initProductInfoList()
    //     this.productSelectCallback(this.dataForm.checkProductId)
    //   }
    //   this.$parent.openProductInfoDialog2(this.dataForm.checkProductId,cb)
    // },
    init(id,property) {
      this.dataForm.id = id || 0
    //  this.dataForm.tableListData = tableListData
      this.deepCategoryMapInit()
      this.relateDeepCategoryMapInit()
      this.initClientInfoList()
      this.productInfoMapInit()
      this.$refs.dialog.initDialog({
        dataForm: this.dataForm,
        config: this.dataFormConfig,
        dataRule: this.getNeedDataRule('contractTime', 'clientId', 'deliveryTime', 'clientContractNo','status'),
        initApi: 'contractApi/contractOrderInfoInfo',
        saveApi: 'contractApi/contractAndOrderSave',
        updateApi: 'contractApi/updateContractAndOrder',
        objectName: 'contractOrderInfo'
      }),
        this.$nextTick(() => {

          if (!this.R.isNil(property)) {
            Object.keys(property).forEach((key) => {
              this.dataForm[key] = property[key]
            })
          }
        })
    }
  }
}
</script>
